package com.local.goods.controller;

import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.PageResultUtil;
import com.local.common.util.ResultUtil;
import com.local.goods.pojo.GoodsCategory;
import com.local.goods.pojo.GoodsCategoryDeleteRequestParam;
import com.local.goods.pojo.GoodsCategoryListRequestParam;
import com.local.goods.service.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 商品分类管理控制器
 */
@Controller
@RequestMapping("/category")
public class GoodsCategoryController {

    @Autowired
    private GoodsCategoryService goodsCategoryService;


    /**
     * 通过id查询商品分类数据
     * @param categoryId
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResultUtil<GoodsCategory> getById(@PathVariable("id") Integer categoryId) {
        if (Objects.isNull(categoryId) || categoryId <= 0) {
            return new ResultUtil(201, "参数错误");
        }
        GoodsCategory goodsCategory = goodsCategoryService.selectById(categoryId);
        if (Objects.nonNull(goodsCategory)) {
            return new ResultUtil(200, "", goodsCategory);
        } else {
            return new ResultUtil(201, "请求失败，请稍后再试");
        }
    }

    /**
     * 查询商品分类列表数据，支持翻页（用于后台）
     * @param requestParam
     * @return
     */
    @GetMapping("/list")
    @ResponseBody
    public ResultUtil list(@RequestBody GoodsCategoryListRequestParam requestParam) {
        if (Objects.isNull(requestParam.getCategoryLevel()) || requestParam.getCategoryLevel().toString().isEmpty()
                || Objects.isNull(requestParam.getParentId()) || requestParam.getParentId().toString().isEmpty()) {
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_EXCEPTION.getCode(), "参数错误");
        }
        Byte categoryLevel = requestParam.getCategoryLevel();
        Integer parentId = requestParam.getParentId();
        Integer page = requestParam.getPage();
        page = Objects.isNull(page) || page <= 0 ? 1 : page;
        Integer limit = requestParam.getLimit();
        limit = Objects.isNull(limit) || limit <= 0 ? 10 : limit;
        String sort = requestParam.getSort();
        sort = Objects.isNull(sort) || sort.isEmpty() ? "category_rank" : sort;
        String order = requestParam.getOrder();
        order = Objects.isNull(order) || order.isEmpty() ? "asc" : order;
        Integer isDeleted = requestParam.getIsDeleted();
        isDeleted = Objects.isNull(isDeleted) || isDeleted.toString().isEmpty() ? -1 : isDeleted;

        PageResultUtil<GoodsCategory> goodsCategoryList = goodsCategoryService.findGoodsCategoryList(parentId, categoryLevel, page, limit, sort, order, isDeleted);
        if (Objects.nonNull(goodsCategoryList)) {
            return new ResultUtil(200, "", goodsCategoryList);
        } else {
            return new ResultUtil(201, "请求失败，请稍后再试");
        }
    }


    /**
     * 新增（用于后台）
     * @param goodsCategory
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
    public ResultUtil save(@RequestBody GoodsCategory goodsCategory) {
        Integer saveResult = goodsCategoryService.save(goodsCategory);
        if (saveResult > 0) {
            return new ResultUtil(200, "新增成功");
        } else {
            return new ResultUtil(201, "新增失败，请稍后再试");
        }
    }


    /**
     * 修改（用于后台）
     * @param goodsCategory
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public ResultUtil update(@RequestBody GoodsCategory goodsCategory) {
        Integer updateResult = goodsCategoryService.update(goodsCategory);
        if (updateResult > 0) {
            return new ResultUtil(200, "修改成功");
        } else {
            return new ResultUtil(201, "修改失败，请稍后再试");
        }
    }


    /**
     * 批量删除（用于后台）
     * @param requestParam
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResultUtil delete(@RequestBody GoodsCategoryDeleteRequestParam requestParam) {
        Integer[] ids = requestParam.getIds();
        Integer adminUserId = requestParam.getAdminUserId();
        String dateTime = requestParam.getDateTime();
        Integer deleteResult = goodsCategoryService.deleteByIds(ids, adminUserId, dateTime);
        if (deleteResult > 0) {
            return new ResultUtil(200, "删除成功");
        } else {
            return new ResultUtil(201, "删除失败，请稍后再试");
        }
    }


    /**
     * 通过parent id选择下级分类列表（用于后台）
     * @param categoryId
     * @return
     */
    @GetMapping("/listForSelect")
    @ResponseBody
    public ResultUtil listForSelect(@RequestParam("categoryId") Integer categoryId) {
        if (Objects.isNull(categoryId)) {
            return new ResultUtil(201, "参数错误");
        }

        List<GoodsCategory> goodsCategories = new ArrayList<>();
        if (categoryId == 0) {
            //查询下一级数据
            goodsCategories = goodsCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(0), 1, 0);
        } else {
            //查询id数据
            GoodsCategory goodsCategory = goodsCategoryService.selectById(categoryId);
            //通过id查询下一级数据
            goodsCategories = goodsCategoryService.selectByLevelAndParentIdsAndNumber(Collections.singletonList(categoryId), (goodsCategory.getCategoryLevel() + 1), 0);
        }
        Map<String, List<GoodsCategory>> categoryListResult = new HashMap<>(4);
        categoryListResult.put("goodsCategories", goodsCategories);

        return new ResultUtil(200, "", categoryListResult);
    }


    /**
     * 商品分类数据（用于网址首页）
     * @return
     */
    @GetMapping("/list/index")
    @ResponseBody
    public ResultUtil getIndexCategoryList() {
        List<GoodsCategory> categoryList = goodsCategoryService.getIndexCategoryList();
        if (Objects.nonNull(categoryList)) {
            return new ResultUtil(200, "", categoryList);
        } else {
            return new ResultUtil(201, "请求失败，请稍后再试");
        }
    }
}
